package com.tangding.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.tangding.common.exception.GException;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.pojo.request.user.LoginParams;
import com.tangding.pojo.response.MessageDto;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年9月12日_上午9:44:13
 *
 */
@RestController
@RequestMapping("/")
public class LoginController {
	
	@RequestMapping(value = {"/index"}, method = RequestMethod.GET)
	public ModelAndView index() throws GException {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null && subject.isAuthenticated()) {
			subject.logout();
		}
		ModelAndView view = new ModelAndView();
		view.setViewName("index");
		return view;
	}
	
	@RequestMapping(value = {"/logout"}, method = RequestMethod.GET)
	public ModelAndView logout() throws GException {
		ModelAndView view = new ModelAndView();
		Subject subject = SecurityUtils.getSubject();
		if (subject != null && subject.isAuthenticated()) {
			subject.logout();
		}
		view.setViewName("redirect:/login.html");
		return view;
	}
	
	@RequestMapping(value = {"", "/", "/login"}, method = RequestMethod.GET)
	public ModelAndView login() throws GException {
		ModelAndView view = new ModelAndView();
		view.setViewName("login");
		return view;
	}
	
	@RequestMapping(value = {"/login"}, method = RequestMethod.POST)
	public MessageDto login(LoginParams params) throws GException {
		UsernamePasswordToken token = new UsernamePasswordToken(params.getUid(), params.getPwd());
		Subject subject = SecurityUtils.getSubject();
		try {
			if (!subject.isAuthenticated()) {
				token.setRememberMe(params.getRememberMe());
				subject.login(token);// 验证角色和权限
			}
		} catch (IncorrectCredentialsException e) {
			throw new GException(ErrorConstants.LOGIN_INCORRECT_CREDENTIALS);
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			throw new GException(ErrorConstants.USER_NOT_FOUND);
		}
		
		return MessageDto.responseSuccess("index");
	}
}